// action: "POP"
// block: ƒ block(prompt)
// createHref: ƒ createHref(location)
// go: ƒ go(n)
// goBack: ƒ goBack()
// goForward: ƒ goForward()
// length: 12
// listen: ƒ listen(listener)
// location: {pathname: "/detail/11", search: "", hash: "", state: undefined}
// push: ƒ push(path, state)
// replace: ƒ replace(path, state)

// 获取location
function getLocation() {
    const pathname = window.location.hash.slice(1);
    return {
        pathname,
    }
}



export default function createHashHistory() {
    let action = 'POP'; // 默认是POP
    let msg;
    let listeners = [];
    let stack = [];
    let stackIndex = -1;
    let location = getLocation();
    // push时保存的pathname
    let pathname;
    window.addEventListener('hashchange', () => {
        // 有可能不是push的，可能是改变导航栏
        pathname = pathname ? pathname : window.location.hash.slice(1)
        // 执行监听的listeners
        listeners.forEach(fn => {
            fn({
                pathname
            })
        });
    }, false)

    // 保证刚开始时有hash
    function ensureSlash() {
        let hash = window.location.hash
        let t;
        if (hash.slice(1) == 'undefined') {
            t = '/';
        } else {
            t = hash.slice(1);
        }
        window.location.hash = '/';
    }
    // 保证导航栏有一个#/
    // ensureSlash();


    function block(message) {
        msg = message;
    }

    function createHref(location) {
        const pathname = location.pathname;
        return '#' + pathname
    }

    // 前进或者后退
    function go(n) {
        action = 'POP';
        stackIndex += n;
        if (stackIndex <= 0) {
            stackIndex = 0;
        } else if (stackIndex >= stack.length) {
            stackIndex =  stack.length - 1;
        }
        // 改更改hash, 也要更改pathname
        window.location.hash = pathname = stack[stackIndex];

    }

    // 后退1
    function goBack() {
        go(-1);
    }

    // 前进1
    function goForward() {
        go(1);
    }

    // 监听函数，当路径发生变化时调用listener
    function listen(listener) {
        listeners.push(listener);
    }

    // 跳转路径
    function push(path, state) {
        // 更改 actions
        action = 'PUSH'
        // 更改location
        location = { ...location, pathname: path, state }
        // 存入栈中
        stack[++stackIndex] = path;
        // 更改pathname并触发更新
        pathname = path;
        window.location.hash = path;
    }

    function replace(path, state) {
        action = 'REPLACE';
        stack[stackIndex] = path;
        location.pathname = path;
        location.state = state;
    }


    return {
        action,
        block,
        createHref,
        go,
        goBack,
        goForward,
        length: stack.length,
        listen,
        location,
        push,
        replace
    }
}